﻿using FE.Service.Contract;
using FE.Shared;
using Newtonsoft.Json;
using System.IO;

namespace FE.Service
{
    public class AppService : IAppService
    {
        private readonly IConfigurationService _configurationService;

        public AppService(IConfigurationService configurationService)
        {
            _configurationService = configurationService;
        }

        public bool SaveAppSettings(AppSettings settings)
        {
            var json = JsonConvert.SerializeObject(settings);

            File.WriteAllText(_configurationService.LocalJsonFilePath, json);

            return false;
        }

        public bool SaveAppSettings(MySqlSettings settings)
        {
            //先获取所有配置
            var app = ReadAppSettings();
            //只修改特定部分
            app.ServerMySqlSettings = settings;

            SaveAppSettings(app);

            return true;
        }

        public bool SaveAppSettings(ServerPathSettings settings)
        {
            //先获取所有配置
            var app = ReadAppSettings();
            //只修改特定部分
            app.ServerPathSettings = settings;

            SaveAppSettings(app);

            return true;
        }

        public AppSettings ReadAppSettings()
        {
            if (File.Exists(_configurationService.LocalJsonFilePath))
            {
                var text = File.ReadAllText(_configurationService.LocalJsonFilePath);
                return JsonConvert.DeserializeObject<AppSettings>(text);
            }

            //如果没有,则初始化为最新的
            return new AppSettings();


        }
    }
}